package org.example.dubbo.samples.async;

import org.apache.dubbo.rpc.RpcContext;
import org.example.dubbo.samples.async.api.AsyncService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AsyncConsumer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/async-consumer.xml");
        context.start();
        AsyncService asyncService = context.getBean("asyncService", AsyncService.class);
        asyncService.sayHello("world");

        CompletableFuture<String> helloFuture = RpcContext.getContext().getCompletableFuture();
        helloFuture.whenComplete((retValue, exception) -> {
            if (exception == null) {
                System.out.println("return value: " + retValue);
            } else {
                exception.printStackTrace();
            }
        });

        CompletableFuture<String> f = RpcContext.getContext().asyncCall(() -> asyncService.sayHello("async call request"));
        System.out.println("async call returned: " + f.get());

        RpcContext.getContext().asyncCall(() -> {
            asyncService.sayHello("one way call request");
        });
    }
}
